from fdfs_client.client import Fdfs_client
from rest_framework import serializers

from apps.goods.models import SKUImage, SKU


from celery_tasks.static_html.tasks import get_detail_html
##########商品图片选项序列化器################
# from apps.goods.utils import get_detail_html


class SKUImageSerializer(serializers.ModelSerializer):



    class Meta:
        model = SKUImage
        fields = "__all__"

    # 重写保存图片表序列化器
    def create(self,validated_data):
        # 1.获取前端的sku对象
        sku = validated_data["sku"]
        # 2.获取前端传递的图片数据
        image=validated_data["image"]
        # 3.链接fadtDFS
        clinet=Fdfs_client("/home/python/Desktop/meiduo/meiduo_46/meiduo_mall/utils/fastdfs/client.conf")

        # 4.上传图片
        res=clinet.upload_by_buffer(image.read())
        # 5.判断上传是否成功
        if res["Status"] != "Upload successed.":
            raise serializers.ValidationError("上传失败")
        # 6.提取链接地址
        path = res.get("Remote file_id")
        # 7.保存图片
        img = SKUImage.objects.create(sku=sku,image=path)

        return img

    #更新重写
    def update(self,instance,validated_data):
        # 1.获取前端的sku对象
        sku = validated_data["sku"]
        # 2.获取前端传递的图片数据
        image=validated_data["image"]
        # 3.链接fadtDFS
        clinet=Fdfs_client("/home/python/Desktop/meiduo/meiduo_46/meiduo_mall/utils/fastdfs/client.conf")

        # 4.上传图片
        res=clinet.upload_by_buffer(image.read())
        # 5.判断上传是否成功
        if res["Status"] != "Upload successed.":
            raise serializers.ValidationError("上传失败")
        # 6.提取链接地址
        path = res.get("Remote file_id")
        # 7.更新保存
        instance.image=path
        instance.save()

        #生成新的静态页面
        # get_detail_html(sku.id)
        #异步任务生成页面静态化
        get_detail_html.delay(sku.id)
        return instance




class SKUSerializer(serializers.ModelSerializer):
    # 商品SKU序列化器

    class Meta:
        model = SKU
        fields = "__all__"